<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户ID" prop="userId" v-hasPermi="['user_device_data:user_device_data:edit']">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备信息" prop="fullName">
        <el-input
          v-model="queryParams.fullName"
          placeholder="请输入设备信息"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['user_device_data:user_device_data:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['user_device_data:user_device_data:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['user_device_data:user_device_data:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['user_device_data:user_device_data:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="user_device_dataList_admin"
              @selection-change="handleSelectionChange"
    >
      <el-table-column  type="selection" width="55" align="center" />
      <el-table-column  label="用户设备数据ID" align="center" prop="dataId" />
      <el-table-column  label="用户ID" align="center" prop="userId"/>
      <el-table-column  label="全名" align="center" prop="fullName" />
      <el-table-column  label="性别" align="center" prop="sex" :formatter="sexFormatter"/>
      <el-table-column  label="年龄" align="center" prop="age" />
      <el-table-column  label="身高" align="center" prop="height" />
      <el-table-column  label="体重" align="center" prop="weight" />
      <el-table-column  label="BMI" align="center" prop="bmi" />
      <el-table-column  label="心率" align="center" prop="heartRate">
        <template slot-scope="scope">
          <el-popover
            placement="top"
            trigger="hover"
            :content="getHeartRateWarning(scope.row.heartRate)"
            :popper-class="getPopoverClass(scope.row.heartRate)"
          >
            <div
              slot="reference"
              :class="['heart-rate-cell', getHeartRateClass(scope.row.heartRate)]"
            >
              {{ scope.row.heartRate }}
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column  label="睡眠质量" align="center" prop="sleepQuality" />
      <el-table-column  label="步数" align="center" prop="steps">
        <template slot-scope="scope">
          <el-popover
            placement="top"
            trigger="hover"
            :content="getStepsWarning(scope.row.steps)"
            :popper-class="getStepsClass(scope.row.steps).replace('-cell', '-popover')"
          >
            <div slot="reference"
                 :class="['heart-rate-cell', getStepsClass(scope.row.steps)]">
              {{ scope.row.steps }}
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column  label="睡眠时间" align="center" prop="sleepDuration">
        <template slot-scope="scope">
          <el-popover
            placement="top"
            trigger="hover"
            :content="getSleepWarning(scope.row.sleepDuration)"
            :popper-class="getSleepClass(scope.row.sleepDuration).replace('-cell', '-popover')"
          >
            <div slot="reference"
                 :class="['heart-rate-cell', getSleepClass(scope.row.sleepDuration)]">
              {{ scope.row.sleepDuration }}
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column  label="运动时长" align="center" prop="activeMinutes" />
      <el-table-column  label="血压收缩压" align="center" prop="bloodPressureSystolic">
        <template slot-scope="scope">
          <el-popover
            placement="top"
            trigger="hover"
            :content="getBloodPressureWarning(scope.row.bloodPressureSystolic, scope.row.bloodPressureDiastolic)"
            :popper-class="getBloodPressureClass(scope.row.bloodPressureSystolic, scope.row.bloodPressureDiastolic).replace('-cell', '-popover')"
          >
            <div slot="reference"
                 :class="['heart-rate-cell', getBloodPressureClass(scope.row.bloodPressureSystolic, scope.row.bloodPressureDiastolic)]">
              {{ scope.row.bloodPressureSystolic }}
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column  label="血压舒张压" align="center" prop="bloodPressureDiastolic">
        <template slot-scope="scope">
          <el-popover
            placement="top"
            trigger="hover"
            :content="getBloodPressureWarning(scope.row.bloodPressureSystolic, scope.row.bloodPressureDiastolic)"
            :popper-class="getBloodPressureClass(scope.row.bloodPressureSystolic, scope.row.bloodPressureDiastolic).replace('-cell', '-popover')"
          >
            <div slot="reference"
                 :class="['heart-rate-cell', getBloodPressureClass(scope.row.bloodPressureSystolic, scope.row.bloodPressureDiastolic)]">
              {{ scope.row.bloodPressureDiastolic }}
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column  label="血氧" align="center" prop="bloodOxygen">
        <template slot-scope="scope">
          <el-popover
            placement="top"
            trigger="hover"
            :content="getBloodOxygenWarning(scope.row.bloodOxygen)"
            :popper-class="getBloodOxygenClass(scope.row.bloodOxygen).replace('-cell', '-popover')"
          >
            <div slot="reference"
                 :class="['heart-rate-cell', getBloodOxygenClass(scope.row.bloodOxygen)]">
              {{ scope.row.bloodOxygen }}
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column  label="日期" align="center" prop="date" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.date, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column  label="备注" align="center" prop="remark" />
      <el-table-column  label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['user_device_data:user_device_data:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['user_device_data:user_device_data:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改用户设备数据对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="全名" prop="fullName">
          <el-input v-model="form.fullName" placeholder="请输入全名" />
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="form.age" placeholder="请输入年龄" />
        </el-form-item>
        <el-form-item label="身高" prop="height">
          <el-input v-model="form.height" placeholder="请输入身高" />
        </el-form-item>
        <el-form-item label="体重" prop="weight">
          <el-input v-model="form.weight" placeholder="请输入体重" />
        </el-form-item>
        <el-form-item label="BMI" prop="bmi">
          <el-input v-model="form.bmi" placeholder="请输入BMI" />
        </el-form-item>
        <el-form-item label="心率" prop="heartRate">
          <el-input v-model="form.heartRate" placeholder="请输入心率" />
        </el-form-item>
        <el-form-item label="睡眠质量" prop="sleepQuality">
          <el-input v-model="form.sleepQuality" placeholder="请输入睡眠质量" />
        </el-form-item>
        <el-form-item label="步数" prop="steps">
          <el-input v-model="form.steps" placeholder="请输入步数" />
        </el-form-item>
        <el-form-item label="睡眠时间" prop="sleepDuration">
          <el-input v-model="form.sleepDuration" placeholder="请输入睡眠时间" />
        </el-form-item>
        <el-form-item label="运动时长" prop="activeMinutes">
          <el-input v-model="form.activeMinutes" placeholder="请输入运动时长" />
        </el-form-item>
        <el-form-item label="血压收缩压" prop="bloodPressureSystolic">
          <el-input v-model="form.bloodPressureSystolic" placeholder="请输入血压收缩压" />
        </el-form-item>
        <el-form-item label="血压舒张压" prop="bloodPressureDiastolic">
          <el-input v-model="form.bloodPressureDiastolic" placeholder="请输入血压舒张压" />
        </el-form-item>
        <el-form-item label="血氧" prop="bloodOxygen">
          <el-input v-model="form.bloodOxygen" placeholder="请输入血氧" />
        </el-form-item>
        <el-form-item label="日期" prop="date">
          <el-date-picker clearable
            v-model="form.date"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listUser_device_data,
  getUser_device_data,
  delUser_device_data,
  addUser_device_data,
  updateUser_device_data,
  getRole
} from '@/api/user_device_data/user_device_data'
import { parseTime } from '@/utils/ruoyi'
import { getInfo } from '@/api/login'

export default {
  name: "User_device_data",
  data() {
    return {
      //是否是管理员显示
      admin:null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户设备数据表格数据
      user_device_dataList_admin: [],
      user_device_dataList_user: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        fullName: null,
        sex: null,
        age: null,
        height: null,
        weight: null,
        BMI: null,
        heartRate: null,
        sleepQuality: null,
        steps: null,
        sleepDuration: null,
        activeMinutes: null,
        bloodPressureSystolic: null,
        bloodPressureDiastolic: null,
        bloodOxygen: null,
        date: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        heartRate: [
          { required: true, message: "心率不能为空", trigger: "blur" }
        ],
        date: [
          { required: true, message: "日期不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {

    this.getIdAndRole()
    // 从路由参数获取设备信息
    const query = this.$route.query;
    this.queryParams.userId = query.userId || '';
    this.queryParams.fullName = query.fullName || '';
    // 初始化加载数据
    this.getList();
    this.getRole();
    console.log(this.queryParams.fullName)
  },
  methods: {
    sexFormatter(row, column, cellValue) {
      return cellValue === 1 ? '男' : '女'
    },
    async getIdAndRole() {
      this.loading = true;
      getInfo().then(response => {
        this.admin = Boolean(response.user.admin); // 强制转换为布尔类型
        this.loading = false;
      });
    },
    // 血压判断方法
    getBloodPressureClass(sys, dia) {
      const systolic = Number(sys)
      const diastolic = Number(dia)
      if (systolic >= 140 || diastolic >= 90) return 'danger-cell'
      else if (systolic >= 130 || diastolic >= 85) return 'warning-cell'
      else if (systolic >= 120 || diastolic >= 80) return 'safe-cell'
      return 'safe-cell'
    },
    getBloodPressureWarning(sys, dia) {
      const systolic = Number(sys)
      const diastolic = Number(dia)
      if (systolic >= 140 || diastolic >= 90)
        return `高血压2级（${systolic}/${diastolic}）需要立即就医`
      if (systolic >= 130 || diastolic >= 85)
        return `高血压1级（${systolic}/${diastolic}）建议密切监测`
      if (systolic >= 120 || diastolic >= 80)
        return `正常高值（${systolic}/${diastolic}）注意生活方式`
      return `血压正常（${systolic}/${diastolic}）保持良好状态`
    },
    // 血氧判断方法
    getBloodOxygenClass(value) {
      const oxygen = Number(value)
      if (oxygen < 90) return 'danger-cell'
      if (oxygen < 95) return 'warning-cell'
      return 'safe-cell'
    },
    getBloodOxygenWarning(value) {
      const oxygen = Number(value)
      if (oxygen < 90) return '严重低血氧！需要立即就医'
      if (oxygen < 95) return '血氧偏低！建议检查呼吸功能'
      return '血氧水平正常，保持良好状态'
    },
    // 睡眠时间判断（单位：小时）
    getSleepClass(value) {
      const hours = Number(value)
      if (hours >= 9) return 'danger-cell'
      if (hours >= 7) return 'safe-cell'
      if (hours >= 6) return 'warning-cell'
      return 'danger-cell'
    },
    getSleepWarning(value) {
      const hours = Number(value)
      if (hours >= 9) return '睡眠时间过长！建议不超过9小时'
      if (hours >= 7) return '睡眠时长正常，保持良好作息'
      if (hours >= 6) return '睡眠不足！建议达到7小时'
      return '严重睡眠不足！需要立即调整'
    },

    // 步数判断（每日）
    getStepsClass(value) {
      const steps = Number(value)
      if (steps > 12000) return 'warning-cell'
      if (steps >= 8000) return 'safe-cell'
      if (steps >= 5000) return 'warning-cell'
      return 'danger-cell'
    },
    getStepsWarning(value) {
      const steps = Number(value)
      if (steps > 12000) return '运动量过大！注意膝盖保护'
      if (steps >= 8000) return '运动量达标，继续保持'
      if (steps >= 5000) return '活动量不足！建议达到8000步'
      return '严重缺乏运动！需要增加活动量'
    },
    // 修改后的心率判断方法
    getHeartRateClass(value) {
      const num = Number(value)
      if (num >= 120) return 'danger-cell'    // 过高危险
      if (num >= 100) return 'warning-cell'   // 过高预警
      if (num >= 70) return 'safe-cell'       // 正常范围
      if (num >= 60) return 'warning-cell'    // 过低预警
      return 'danger-cell'                    // 过低危险
    },
    getHeartRateWarning(value) {
      const num = Number(value)
      if (num >= 120) return '心率过高危险！建议立即检查'
      if (num >= 100) return '心率过高预警！建议关注'
      if (num >= 70) return '心率正常，继续保持'
      if (num >= 60) return '心率过低预警！建议关注'
      return '心率过低危险！需要立即干预'
    },
    getPopoverClass(value) {
      const num = Number(value)
      if (num >= 120) return 'danger-popover'
      if (num >= 100) return 'warning-popover'
      if (num >= 70) return 'safe-popover'
      if (num >= 60) return 'warning-popover'
      return 'danger-popover'
    },

    /** 查询用户设备数据列表 */
    getList() {
      this.loading = true;
      listUser_device_data(this.queryParams).then(response => {
        this.user_device_dataList_user = response.rows;
        this.user_device_dataList_admin = response.rows
        this.total = response.total;
        console.log('原始数据:', response.rows[0])
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        dataId: null,
        userId: null,
        fullName: null,
        sex: null,
        age: null,
        height: null,
        weight: null,
        bmi: null,
        heartRate: null,
        sleepQuality: null,
        steps: null,
        sleepDuration: null,
        activeMinutes: null,
        bloodPressureSystolic: null,
        bloodPressureDiastolic: null,
        bloodOxygen: null,
        date: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.dataId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户设备数据";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const dataId = row.dataId || this.ids
      getUser_device_data(dataId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改用户设备数据";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.dataId != null) {
            updateUser_device_data(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUser_device_data(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const dataIds = row.dataId || this.ids;
      this.$modal.confirm('是否确认删除用户设备数据编号为"' + dataIds + '"的数据项？').then(function() {
        return delUser_device_data(dataIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('user_device_data/user_device_data/export', {
        ...this.queryParams
      }, `user_device_data_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>
/* 心率单元格样式 */
.heart-rate-cell {
  overflow: hidden;
  display: inline-block;
  width: 100%;
  padding: 8px 12px;
  border-radius: 16px;
  font-weight: 700;
  transition: all 0.3s;
  text-align: center;
  white-space: nowrap;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
/* 安全状态 */
.safe-cell {
  background: #f6ffed;
  border: 2px solid #b7eb8f;
  color: #52c41a;
}
/* 预警状态 */
.warning-cell {
  background: #fffbe6;
  border: 2px solid #ffe58f;
  color: #faad14;
  animation: pulse-warning 1.5s infinite;
}
/* 危险状态 */
.danger-cell {
  background: #fff1f0;
  border: 2px solid #ffccc7;
  color: #ff4d4f;
  animation: pulse-danger 0.8s infinite;
}
/* 深度选择器覆盖popover样式 */
:deep(.safe-popover) {
  border: 2px solid #b7eb8f !important;
  background: #f6ffed !important;
}

:deep(.safe-popover .el-popover__title) {
  background: #b7eb8f !important;
  color: #237804 !important;
}

:deep(.warning-popover) {
  border: 2px solid #ffe58f !important;
  background: #fffbe6 !important;
}

:deep(.warning-popover .el-popover__title) {
  background: #ffe58f !important;
  color: #ad6800 !important;
}

:deep(.danger-popover) {
  border: 2px solid #ffccc7 !important;
  background: #fff1f0 !important;
}

:deep(.danger-popover .el-popover__title) {
  background: #ffccc7 !important;
  color: #cf1322 !important;
}
/* 补全动画效果 */
@keyframes pulse-warning {
  0% { transform: scale(1); }
  50% { transform: scale(1.05); }
  100% { transform: scale(1); }
}

@keyframes pulse-danger {
  0% { transform: scale(1); }
  50% { transform: scale(1.1); }
  100% { transform: scale(1); }
}

/* 增强单元格视觉效果 */
.heart-rate-cell {
  margin: 2px 0;
  min-width: 60px;
  letter-spacing: 0.5px;
  text-shadow: 0 1px 1px rgba(0,0,0,0.1);
}

/* 完善弹出框细节 */
:deep(.el-popover) {
  min-width: 180px;
  border-width: 2px!important;
  font-family: Arial, sans-serif;
}

:deep(.el-popover__title) {
  font-weight: bold;
  font-size: 15px;
  padding: 10px 15px;
  border-bottom: 2px solid;
}

:deep(.el-popover__content) {
  font-size: 13px;
  line-height: 1.6;
  padding: 12px 15px;
}

/* 安全状态增强 */
.safe-cell:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(92,184,92,0.2);
}

/* 危险状态闪烁增强 */
.danger-cell {
  animation: pulse-danger 0.6s ease-in-out infinite;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .heart-rate-cell {
    padding: 6px 8px;
    font-size: 12px;
  }

  :deep(.el-popover) {
    min-width: 140px;
    font-size: 12px;
  }
}
/* 新增低心率状态提示样式 */
:deep(.warning-popover) .el-popover__content {
  color: #d48806 !important;
}
:deep(.danger-popover) .el-popover__content {
  color: #cf1322 !important;
}


</style>
